//
//  DetailViewController.swift
//  EnglishDictionary
//
//  Created by QFX on 2024/2/23.
//

import UIKit
import CenteredCollectionView

class DetailViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout  {
    let cellPercentWidth: CGFloat = 0.7
    let cellPercentHeight: CGFloat = 0.7
    var centeredCollectionViewFlowLayout: CenteredCollectionViewFlowLayout = CenteredCollectionViewFlowLayout()
    var word:Word?
    var sentence:Sentence?

    var navTitle:String?
    var words:[Word]?
    var sentences:[Sentence]?
    var collectSelectDict:[String : String] = [:]

    var timer:Timer?
    var isAutoScroll:Bool = false
    var currentRow:Int = 0
    var isPause:Bool = false
    var type:Int = 0;//0:单词 1：句子
    var isSort:Bool = false
    var isOpenEye:Bool =  true
    var categoryTitle:String?

    @IBOutlet weak var openEyesView: UIView!
    @IBOutlet weak var openEyesButton: UIButton!
    @IBOutlet weak var playCLabel: UILabel!
    @IBOutlet weak var leftPlayView: UIView!
    @IBOutlet weak var rightPlayView: UIView!
    @IBOutlet weak var autoPlayButton: UIButton!
    @IBOutlet weak var autoPlayView: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.isAutoScroll = false
        SpeechSynthesizer.Shared.stopSpeak()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        // Get the reference to the CenteredCollectionViewFlowLayout (REQURED)
//        centeredCollectionViewFlowLayout = (collectionView.collectionViewLayout as! CenteredCollectionViewFlowLayout)

//        self.view.backgroundColor = UIColor(red: 0, green: 255, blue: 0, alpha: 0.3)
        self.view.backgroundColor = .white
        // Modify the collectionView's decelerationRate (REQURED)
        collectionView.decelerationRate = UIScrollView.DecelerationRate.fast

        // Assign delegate and data source
        collectionView.delegate = self
        collectionView.dataSource = self

        // Configure the required item size (REQURED)
        centeredCollectionViewFlowLayout.itemSize =  CGSize(
            width: UIScreen.main.bounds.width - 40,
            height: UIScreen.main.bounds.height  * cellPercentHeight
        )
//         Configure the optional inter item spacing (OPTIONAL)
        centeredCollectionViewFlowLayout.minimumLineSpacing = 20
        
        collectionView.collectionViewLayout = centeredCollectionViewFlowLayout
//        collectionView.collectionViewLayout =  listCollectionFlowLayout
        collectionView.register(UINib(nibName: "DetailViewCell", bundle: nil), forCellWithReuseIdentifier: "DetailViewCell")
        
        self.autoPlayView.layer.cornerRadius = 30
        self.autoPlayView.clipsToBounds = true
        
        self.openEyesView.layer.cornerRadius = 30
        self.openEyesView.clipsToBounds = true
        

        self.getData()
        
        self.navigationItem.title = navTitle
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            if self.type == 1{
                if let index = self.sentences?.firstIndex(where: { wd in
                    return wd.sentence == self.sentence?.sentence
                }){
                    self.currentRow = index
                    self.collectionView.scrollToItem(at: IndexPath(row: index, section: 0), at: .right, animated: false)
                }
            }else if self.type == 0{
                if let index = self.words?.firstIndex(where: { wd in
                    return wd.word == self.word?.word
                }){
                    self.currentRow = index
                    self.collectionView.scrollToItem(at: IndexPath(row: index, section: 0), at: .right, animated: false)
                }
            }
        }
            
        self.leftPlayView.layer.cornerRadius = 30
        self.leftPlayView.clipsToBounds = true
        
        self.rightPlayView.layer.cornerRadius = 30
        self.rightPlayView.clipsToBounds = true
        
        let name = self.isAutoScroll ? "pause":"playBt"
        self.autoPlayButton.setImage(UIImage(named:name ), for: .normal)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "收藏合集", style: .plain, target: self, action: #selector(collect))
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "loginBack"), style: .plain, target: self, action: #selector(back))
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.autoPlay()
        }
        
        kNOTIFY_ADD(observer: self, selector: #selector(reloadData), name: "cpSuccess", object: nil)
    }

    @objc func reloadData() {
        getData()
    }
    
    @objc func getData(){
        if let fold = navTitle{
            if (self.categoryTitle == "Sentences"){
                self.playCLabel.text = "播放句子"
                self.type = 1
                self.sentences = Sentence.getSentence(fold: fold)
                if isSort {
                    self.sentences = self.sentences?.sorted(by: { w1, w2 in
                        return w1.sentence! < w2.sentence!
                    })
                }
            }else{
                self.type = 0
                self.playCLabel.text = "播放单词"
                self.words = Word.getWords(fold: fold)
                if isSort {
                    self.words = self.words?.sorted(by: { w1, w2 in
                        return w1.word! < w2.word!
                    })
                }
            }
        }
        self.collectionView.reloadData()
    }
    

    @objc func back(){
        self.isAutoScroll = false
        if  let collects = Collection.getCollection(fold: "收藏合集", type: self.type){
            if collects.count > 0 {
                let al = UIAlertController.init(title: "提示", message:"是否清空收藏合集", preferredStyle: .alert)
                let ac_cancel = UIAlertAction.init(title: "取消", style:  .cancel){_ in
                    self.navigationController?.popViewController(animated: true)
                }
                let ac_confirm = UIAlertAction.init(title: "确定", style:  .destructive){_ in
                    for collect in collects{
                        try?collect.delete()
                    }
                    self.navigationController?.popViewController(animated: true)
                }
                al.addAction(ac_cancel)
                al.addAction(ac_confirm)
                self.present(al, animated: true)
            }else{
                self.navigationController?.popViewController(animated: true)
            }
        }else{
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc func collect(){
        if  let collects = Collection.getCollection(fold: "收藏合集", type: self.type){
            if collects.count > 0 {
                let st = UIStoryboard.init(name: "Main", bundle: nil)
                let vc = st.instantiateViewController(withIdentifier: "CollectionViewController") as! CollectionViewController
                vc.navTitle = self.navTitle
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
     }
    
    @IBAction func pause(_ sender: Any) {
        self.isAutoScroll = !self.isAutoScroll
        let name = self.isAutoScroll ? "pause":"playBt"
        self.autoPlayButton.setImage(UIImage(named:name ), for: .normal)
        self.autoPlay()
    }
    
    func autoPlay() {
        if (self.isAutoScroll){
            self.play(row: self.currentRow) { finish in
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    if (self.isAutoScroll){
                        self.currentRow += 1
                        self.collectionView.scrollToItem(at: IndexPath(row: self.currentRow, section: 0), at: .right, animated: true)
                        self.autoPlay()
                    }
                }
            }
        }
    }
    
    @objc func play(row:Int,speekFinsh:@escaping ((String?)-> Void)){
        if self.type == 1{
            let sentence = self.sentences?[row];
            if let wd = sentence?.sentence{
//                SpeechSynthesizer.Shared.speak(wd,language:"en-US",speekFinsh:speekFinsh)
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    speekFinsh(wd)
                }
            }
        }else{
            let word = self.words?[row];
            if let wd =  word?.word{
                SpeechSynthesizer.Shared.speak(wd,language:"en-US",speekFinsh:speekFinsh)
            }
        }

    }
    @IBAction func leftPlay(_ sender: Any) {
        if self.currentRow == 0{
            return
        }
        self.currentRow -= 1
        self.collectionView.scrollToItem(at: IndexPath(row: self.currentRow, section: 0), at: .right, animated: true)
    }
    
    @IBAction func rightPlay(_ sender: Any) {
        if self.currentRow == (self.words?.count ?? 0) - 1{
            return
        }
        self.currentRow += 1
        self.collectionView.scrollToItem(at: IndexPath(row: self.currentRow, section: 0), at: .right, animated: true)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    @IBAction func openEyes(_ sender: Any) {
        self.isOpenEye = !self.isOpenEye
        let image = self.isOpenEye ? UIImage(named: "close_eyes_black") :  UIImage(named: "open_eyes_black")
        let title = self.isOpenEye ? "隐藏释义"  : "显示释义"

        self.openEyesButton.setImage(image, for: .normal)
        self.openEyesButton.setTitle(title, for: .normal)

        self.collectionView.reloadData()
    }
}


extension DetailViewController {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("Selected Cell #\(indexPath.row)")
    }
}

extension DetailViewController {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(
            width: UIScreen.main.bounds.width - 40,
            height: UIScreen.main.bounds.height  * cellPercentHeight
        )
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.type == 0 ? self.words?.count ?? 0 : self.sentences?.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: "DetailViewCell"), for: indexPath) as! DetailViewCell
        cell.layer.cornerRadius = 20
        cell.clipsToBounds = true
//        cell.backgroundColor = .white
        
        let row = indexPath.row
        if self.type == 0{
            let word = self.words?[row]
            cell.titleLabel.text = word?.word
            cell.detailLabel.text = self.isOpenEye ? word?.st : ""
            cell.titleLabel.textAlignment = .center
            cell.detailLabel.textAlignment = .center
            cell.playButton.tag = row
            cell.editButton.tag = row
            cell.collectButton.tag = row
            cell.playButton.addTarget(self, action: #selector(play(sender:)), for: .touchUpInside)
            cell.editButton.addTarget(self, action: #selector(edit(sender:)), for: .touchUpInside)
            cell.collectButton.addTarget(self, action: #selector(self.collection(sender: )), for: .touchUpInside)
            let key = String(format: "%d", row)
            if  let value =  self.collectSelectDict[key]{
                let isSelect = Int(value) == 1
                cell.collectButton.isSelected = isSelect
            }else{
                cell.collectButton.isSelected = false
            }
        }else if self.type == 1 {
            let sentence = self.sentences?[row]
            cell.titleLabel.textAlignment = .left
            cell.detailLabel.textAlignment = .left
            cell.titleLabel.text = sentence?.sentence
            cell.titleLabel.font = UIFont.systemFont(ofSize: 30)
            cell.detailLabel.text = self.isOpenEye ? sentence?.st : ""
            cell.playButton.tag = row
            cell.editButton.tag = row
            cell.collectButton.tag = row
            cell.playButton.addTarget(self, action: #selector(play(sender:)), for: .touchUpInside)
            cell.editButton.addTarget(self, action: #selector(edit(sender:)), for: .touchUpInside)
            cell.collectButton.addTarget(self, action: #selector(self.collection(sender: )), for: .touchUpInside)
            let key = String(format: "%d", row)
            if  let value =  self.collectSelectDict[key]{
                let isSelect = Int(value) == 1
                cell.collectButton.isSelected = isSelect
            }else{
                cell.collectButton.isSelected = false
            }
        }

        return cell
    }
    
    @objc func collection(sender:UIButton){
        let row = sender.tag
        sender.isSelected = !sender.isSelected
        self.collectionView.reloadData()
        let key = String(format: "%d", row)
        let value = String(format: "%d", sender.isSelected)
        self.collectSelectDict.updateValue(value, forKey: key)
        if self.type == 0{
            let word = self.words?[row]
            let collect = Collection()
            collect.word = word?.word
            collect.st = word?.st
            collect.type = 0
            collect.fold = "收藏合集"
            try?collect.saveOrUpdate()
        }else if self.type == 1 {
            let sentence = self.sentences?[row]
            let collect = Collection()
            collect.sentence = sentence?.sentence
            collect.st = sentence?.st
            collect.type = 1
            collect.fold = "收藏合集"
            try?collect.saveOrUpdate()
        }
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.currentRow = centeredCollectionViewFlowLayout.currentCenteredPage ?? 0
        print("Current centered index: \(String(describing: centeredCollectionViewFlowLayout.currentCenteredPage ?? nil))")
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        print("Current centered index: \(String(describing: centeredCollectionViewFlowLayout.currentCenteredPage ?? nil))")
    }
    
    @objc func edit(sender:UIButton){
        let tag = sender.tag
        if self.type == 0{
            let word = self.words?[tag];
            let st = UIStoryboard.init(name: "Main", bundle: nil)
            let vc = st.instantiateViewController(withIdentifier: "insertDictionaryViewController") as! insertDictionaryViewController
            vc.word = word
            self.navigationController?.pushViewController(vc, animated: true)
        }else if self.type == 1{
            let sentence = self.sentences?[tag];
            let st = UIStoryboard.init(name: "Main", bundle: nil)
            let vc = st.instantiateViewController(withIdentifier: "insertDictionaryViewController") as! insertDictionaryViewController
            vc.sentence = sentence
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    

    
    
    @objc func play(sender:UIButton){
        let tag = sender.tag
        if self.type == 0{
            let word = self.words?[tag];
            if let wd = word?.word{
                SpeechSynthesizer.Shared.speak(wd,language:"en-US") { wd in
//                    if let tr = word!.st{
//                        SpeechSynthesizer.Shared.speak(tr,language:"zh-CN")
//                    }
                }
            }
        }else if self.type == 1{
            let sentence = self.sentences?[tag];
            if let wd = sentence?.sentence{
//                SpeechSynthesizer.Shared.speak(wd,language:"en-US") { wd in
//                    if let tr = sentence!.st{
//                        SpeechSynthesizer.Shared.speak(tr,language:"zh-CN")
//                    }
//                }
            }
        }
    }
}
 
